<?php
namespace app\wechat\controller;

use app\common\controller\AdminBaseController;
use app\wechat\model\WechatUser as UserModel;
/**
 * 微信粉丝
 */
class User extends AdminBaseController {

	protected $user_model;

	protected function _initialize() {
		parent::_initialize();
		$this -> user_model = new UserModel();
	}

	/**
	 * 粉丝列表
	 * @return mixed
	 */
	public function index() {
		$user_list = $this -> user_model -> order('subscribe_time desc') -> paginate(15);
		$this -> assign('user_list', $user_list);
		return $this -> fetch();
	}

	/**
	 * 获得所有粉丝，最多1w
	 * @return mixed
	 */
	public function lists() {

		$wechat = load_wechat('User');
		$openid = '';
		$result = $wechat -> getUserList($openid);
		if ($result === false) {
			$this -> error('同步粉丝失败');
		}
		// 粉丝openid集合
		$fans = $result['data']['openid'];
		$users = array();
		foreach ($fans as $fan) {
			$user = $wechat -> getUserInfo($fan);
			$users[] = $user;
		}
		$result2 = db() -> query('truncate ' . config('database.prefix') . 'wechat_user');
		$result3 = $this -> user_model -> allowField(true) -> saveAll($users);
		if ($result2 !== false && $result3) {
			$this -> error('同步粉丝成功', url('user/index'));
		} else {
			$this -> error('同步粉丝失败', url('user/index'));
		}

	}

}
